import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

// createRouter创建路由实例
// 配置history模式
// 1、history模式： ceateWebHistory 地址栏不带#
// 2.hash模式：createWebHasgHistoty 地址栏带#
// vite中的环境变量import.meta.env.BASE_URL 地址栏的首部,前缀默认是
// 登录访问拦截器，使用beforeEach 返回值 undefied直接放行 false拦截回from的地址
// 如果访问没有token,且访问的是非登录页的就拦截回login页

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  // 如果没有token则是访问的非登录页，然乎返回
  if (!userStore.token && to.path !== '/login') return '/login'
})
export default router
